package com;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConfigAnalyzer {

    public static void main(String[] args) {

        String filePath = "D:\\data\\1.cz"; // 替换为你的文件路径
        List<String> lines = new ArrayList<>();
        // 模拟数据，实际应用中应从文件读取
        Map<String, String> configMap = new HashMap<>();

        int m = 1;
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                if(line.indexOf("=") > 0) {
                    String tmp = line.substring(line.indexOf("=") + 1);
                    String key = line.substring(0, line.indexOf("="));
//                    System.out.println(tmp);
                    configMap.put(key, tmp);
//                    System.out.println("\"configMap.put(\"" + key + "\"", "\" + tmp + \"" +");");
                    System.out.println("configMap.put(\"" + key + "\", \"" + tmp + "\");");

//                    lines.add(tmp);
                }
                m++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        // 模拟数据，实际应用中应从文件读取
//        Map<String, String> configMap = new HashMap<>();
//        // 示例数据
//        configMap.put("Config1", "025040000401");
//        configMap.put("Config2", "025040000401");
//        configMap.put("Config5", "020035000401");
        // ... 继续添加其他Config数据

        // 分析配置
        analyzeConfigs(configMap);
    }

    public static void analyzeConfigs(Map<String, String> configMap) {
        int totalBoxes = 16; // 总共有16个针盒
        int holesPerBox = 50; // 每个针盒有50个孔
        int totalHoles = totalBoxes * holesPerBox; // 总共800个孔

        // 创建一个列表来存储所有孔位的数据，按顺序填充
        List<String> configList = new ArrayList<>();
        for (int i = 1; i <= totalHoles; i++) {
            String key = "Config" + i;
            String value = configMap.getOrDefault(key, ""); // 如果不存在，默认为空
            // 将空格也视为没有料号
            if (value.trim().isEmpty()) {
                configList.add("");
            } else {
                configList.add(value);
            }
        }

        List<Map<Integer, String>> boxDataList = new ArrayList<>(); // 存储每个盒子的数据
        Map<String, List<Integer>> fullBoxMaterialBoxNumbers = new HashMap<>(); // 满盒料号对应的盒子编号
        Map<String, List<Integer>> nonFullBoxMaterialPositions = new HashMap<>(); // 非满盒料号位置

        for (int boxIndex = 0; boxIndex < totalBoxes; boxIndex++) {
            int startIndex = boxIndex * holesPerBox;
            int endIndex = startIndex + holesPerBox;
            List<String> currentBox = configList.subList(startIndex, endIndex);

            // 记录当前盒子的全局孔位起始位置（1-based）
            int globalStartIndex = boxIndex * holesPerBox + 1;
            int globalEndIndex = globalStartIndex + holesPerBox - 1;

            // 检查是否为空盒
            boolean isEmptyBox = true;
            for (String hole : currentBox) {
                if (!hole.isEmpty()) {
                    isEmptyBox = false;
                    break;
                }
            }

            Map<Integer, String> boxData = new HashMap<>();
            boxData.put(boxIndex + 1, ""); // 初始化盒子号，值为空

            if (isEmptyBox) {
                // 空盒
                boxData.put(boxIndex + 1, "");
            } else {
                // 检查是否为满盒
                String firstMaterial = currentBox.get(0);
                boolean isFullBox = true;
                boolean hasEmptyHole = false;
                boolean isMixedBox = false;

                for (String hole : currentBox) {
                    if (hole.isEmpty()) {
                        hasEmptyHole = true;
                        break;
                    }
                    if (!hole.equals(firstMaterial)) {
                        isFullBox = false;
                        isMixedBox = true;
                    }
                }

                if (isFullBox && !hasEmptyHole) {
                    // 满盒
                    boxData.put(boxIndex + 1, firstMaterial);
                    // 记录满盒料号对应的盒子编号
                    fullBoxMaterialBoxNumbers.computeIfAbsent(firstMaterial, k -> new ArrayList<>())
                            .add(boxIndex + 1);
                } else {
                    // 构建非满盒的输出字符串
                    if (isMixedBox && !hasEmptyHole) {
                        // 混针盒
                        StringBuilder sb = new StringBuilder();
//                        sb.append("混针盒: ");
                        for (int i = 0; i < currentBox.size(); i++) {
                            if (i > 0) {
                                sb.append(", ");
                            }
                            sb.append(currentBox.get(i));
                        }
                        boxData.put(boxIndex + 1, sb.toString());
                    } else {
                        // 非满盒
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < currentBox.size(); i++) {
                            if (i > 0) {
                                sb.append(", ");
                            }
                            sb.append(currentBox.get(i).isEmpty() ? "" : currentBox.get(i));
                        }
                        boxData.put(boxIndex + 1, sb.toString());
                    }

                    // 记录非满盒中每个料号的孔位位置
                    for (int i = 0; i < currentBox.size(); i++) {
                        String material = currentBox.get(i);
                        if (!material.isEmpty()) {
                            // 计算全局孔位位置
                            int globalHoleIndex = globalStartIndex + i;
                            // 记录料号位置
                            nonFullBoxMaterialPositions.computeIfAbsent(material, k -> new ArrayList<>())
                                    .add(globalHoleIndex);
                        }
                    }
                }
            }

            boxDataList.add(boxData);
        }

        // 构建 boxDataList 的 JSON 对象
        JSONArray boxDataJsonArray = new JSONArray();
        for (Map<Integer, String> boxData : boxDataList) {
            for (Map.Entry<Integer, String> entry : boxData.entrySet()) {
                int boxId = entry.getKey();
                String boxContent = entry.getValue();

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("boxId", boxId);

                if ("".equals(boxContent)) {
                    jsonObject.put("boxType", "EMPTY");
                    jsonObject.put("drillInfos", "");
                } else if (boxContent.contains(",")) {
                    jsonObject.put("boxType", "MIX");
                    jsonObject.put("drillInfos", boxContent);
                } else {
                    jsonObject.put("boxType", "FULL");
                    jsonObject.put("drillInfos", boxContent);
                }

                boxDataJsonArray.add(jsonObject);
            }
        }

        // 构建 fullBoxMaterialBoxNumbers 的 JSON 对象
        JSONObject fullBoxJsonObject = new JSONObject();
        for (Map.Entry<String, List<Integer>> entry : fullBoxMaterialBoxNumbers.entrySet()) {
            JSONArray boxNumbers = new JSONArray();
            for (Integer boxNumber : entry.getValue()) {
                boxNumbers.add(boxNumber);
            }
            fullBoxJsonObject.put(entry.getKey(), boxNumbers);
        }

        // 构建 nonFullBoxMaterialPositions 的 JSON 对象
        JSONObject nonFullBoxJsonObject = new JSONObject();
        for (Map.Entry<String, List<Integer>> entry : nonFullBoxMaterialPositions.entrySet()) {
            JSONArray positions = new JSONArray();
            for (Integer position : entry.getValue()) {
                positions.add(position);
            }
            nonFullBoxJsonObject.put(entry.getKey(), positions);
        }

        // 输出 JSON 数据
        System.out.println("boxDataList JSON 数据：");
        System.out.println(boxDataJsonArray.toString());

        System.out.println("\nfullBoxMaterialBoxNumbers JSON 数据：");
        System.out.println(fullBoxJsonObject.toString());

        System.out.println("\nnonFullBoxMaterialPositions JSON 数据：");
        System.out.println(nonFullBoxJsonObject.toString());

        // 解析 JSON 数据
        parseJsonData(boxDataJsonArray, fullBoxJsonObject, nonFullBoxJsonObject);
    }

    public static void parseJsonData(JSONArray boxDataJsonArray, JSONObject fullBoxJsonObject, JSONObject nonFullBoxJsonObject) {
        // 解析 boxDataJsonArray
        System.out.println("\n解析 boxDataJsonArray：");
        for (int i = 0; i < boxDataJsonArray.size(); i++) {
            JSONObject boxData = boxDataJsonArray.getJSONObject(i);
            int boxId = boxData.getInteger("boxId");
            String boxType = boxData.getString("boxType");
            String drillInfos = boxData.getString("drillInfos");

            System.out.println("盒子 " + boxId + " 类型: " + boxType + ", 信息: " + drillInfos);
        }

        // 解析 fullBoxJsonObject
        System.out.println("\n解析 fullBoxJsonObject：");
        for (String material : fullBoxJsonObject.keySet()) {
            JSONArray boxNumbers = fullBoxJsonObject.getJSONArray(material);
            System.out.println("料号 " + material + " 出现在盒子: " + boxNumbers.toString());
        }

        // 解析 nonFullBoxJsonObject
        System.out.println("\n解析 nonFullBoxJsonObject：");
        for (String material : nonFullBoxJsonObject.keySet()) {
            JSONArray positions = nonFullBoxJsonObject.getJSONArray(material);
            System.out.println("料号 " + material + " 出现在位置: " + positions.toString());
        }
    }
}
